package com.brtbeacon.demo.lot.speech;

import android.content.Context;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.tts.auth.AuthInfo;
import com.baidu.tts.client.SpeechSynthesizer;
import com.baidu.tts.client.TtsMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class BaiduSoundUtil {

    static String appId="19572294";
    static String appKey="a5zc4IAowKnVmFv1bIgqiGGN";
    static String secretKey="HtOY6Pum87Gz210NzZbo87uwqVpzKPgU";
    // TtsMode.MIX; 离在线融合，在线优先； TtsMode.ONLINE 纯在线； 没有纯离线
    static TtsMode ttsMode = TtsMode.MIX;
    //  TtsMode.MIX;模式下，需要复制下面两个数据文件到SD卡
    static String ttsTextDataFileName = "bd_etts_text.dat";
    static String ttsTextDataPath;
    static String ttsModelDataFileName = "bd_etts_common_speech_f7_mand_eng_high_am-mix_v3.0.0_20170512.dat";
    static String ttsModelDataPath;
    static SpeechSynthesizer mSpeechSynthesizer;


    public static String init(Context context) {

        if (mSpeechSynthesizer != null)
            return "1";

        mSpeechSynthesizer = SpeechSynthesizer.getInstance();
        mSpeechSynthesizer.setContext(context);
        mSpeechSynthesizer.setAppId(appId);
        mSpeechSynthesizer.setApiKey(appKey, secretKey);

        AuthInfo authInfo = mSpeechSynthesizer.auth(ttsMode);
        if (!authInfo.isSuccess()) {
            mSpeechSynthesizer = null;
            return "0";
        }

        if (TextUtils.isEmpty(ttsTextDataPath)) {
            ttsTextDataPath = context.getExternalFilesDir("") + ttsTextDataFileName;
        }

        if (TextUtils.isEmpty(ttsModelDataPath)) {
            ttsModelDataPath = context.getExternalFilesDir("") + ttsModelDataFileName;
        }

        // 5. 以下setParam 参数选填。不填写则默认值生效
        // 设置在线发声音人： 0 普通女声（默认） 1 普通男声 2 特别男声 3 情感男声<度逍遥> 4 情感儿童声<度丫丫>
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEAKER, "0");
        // 设置合成的音量，0-9 ，默认 5
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_VOLUME, "9");
        // 设置合成的语速，0-9 ，默认 5
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEED, "5");
        // 设置合成的语调，0-9 ，默认 5
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_PITCH, "5");

        if (initSpeechDataFile(context)) {
            // MIX_MODE_HIGH_SPEED_SYNTHESIZE_WIFI wifi状态下使用在线，非wifi离线。在线状态下， 请求超时1.2s自动转离线
            mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_MIX_MODE, SpeechSynthesizer.MIX_MODE_HIGH_SPEED_SYNTHESIZE_WIFI);
            // 设置本地文本数据
            mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_TEXT_MODEL_FILE, ttsTextDataPath);
            // 设置本地语音数据
            mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_SPEECH_MODEL_FILE, ttsModelDataPath);
        } else {
            mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_MIX_MODE, SpeechSynthesizer.MIX_MODE_DEFAULT);
            mSpeechSynthesizer.setAudioStreamType(AudioManager.MODE_IN_CALL);
        }

        if(mSpeechSynthesizer.initTts(ttsMode) != 0) {
            mSpeechSynthesizer = null;
            return "0";
        }

        return  "1";
    }

    private static boolean initSpeechDataFile(Context context) {
        try {
            copyAssetsFile(context, ttsTextDataFileName, ttsTextDataPath);
            copyAssetsFile(context, ttsModelDataFileName, ttsModelDataPath);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private static void copyAssetsFile(Context context, String sourceFilename, String destPath) throws IOException {
        File file = new File(destPath);
        if (file.exists())
            return;
        AssetManager assets = context.getApplicationContext().getAssets();
        copyFromAssets(assets, sourceFilename, destPath, true);
    }

    public static void copyFromAssets(AssetManager assets, String source, String dest, boolean isCover)
            throws IOException {
        File file = new File(dest);
        if (isCover || (!isCover && !file.exists())) {
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = assets.open(source);
                String path = dest;
                fos = new FileOutputStream(path);
                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = is.read(buffer, 0, 1024)) >= 0) {
                    fos.write(buffer, 0, size);
                }
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (Exception e) {}
                }

                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {}
                }
            }
        }
    }

    public static void speak(String TEXT) {
        if (mSpeechSynthesizer == null) {
            print("[ERROR], 初始化失败");
            return;
        }
        int result = mSpeechSynthesizer.speak(TEXT);
        // mShowText.setText("");
        print("合成并播放 按钮已经点击");
        // checkResult(result, "speak");
    }

    public static void stop() {
        if (mSpeechSynthesizer != null) {
            mSpeechSynthesizer.stop();
        }
    }

    static void print(String message) {
        Log.i("tag", message);
        // mShowText.append(message + "\n");
    }


    /**
     * 检查appId ak sk 是否填写正确，另外检查官网应用内设置的包名是否与运行时的包名一致。本demo的包名定义在build.gradle文件中
     *
     * @return
     */
    static boolean checkAuth() {
        AuthInfo authInfo = mSpeechSynthesizer.auth(ttsMode);
        if (!authInfo.isSuccess()) {
            // 离线授权需要网站上的应用填写包名。本demo的包名是com.baidu.tts.sample，定义在build.gradle中
            String errorMsg = authInfo.getTtsError().getDetailMessage();
            //      print("【error】鉴权失败 errorMsg=" + errorMsg);
            return false;
        } else {
            //     print("验证通过，离线正式授权文件存在。");
            return true;
        }
    }

}
